import React from "react";
import { Form, Input, Button, message as antdMessage } from "antd";
import axios from "axios";
import { useNavigate } from 'react-router-dom'
const Index = () => {
  // 获取跳转 hooks
  const navigate = useNavigate();
  // 获取form 实例
  const [form] = Form.useForm();
  // 登录
  const onFinish = (value) => {
    axios.post("/api/login", value).then((resp) => {
      const { code, message, data } = resp.data;

      if (code === 200) {
        // 登录成功
        antdMessage.success(message);

        // 保存用户数据
        const { userInfo, token } = data;
        localStorage.setItem("token", token);
        localStorage.setItem("userInfo", JSON.stringify(userInfo));

        // 跳转页面 进入首页
        navigate('/')

      } else {
        // 失败
        antdMessage.error(message);
      }
    });
  };
  return (
    <div className="login">
      <div className="content">
        <Form
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
          onFinish={onFinish}
          form={form}
        >
          <Form.Item wrapperCol={{ span: 24 }}>
            <h3 style={{ textAlign: "center" }}>用户登录</h3>
          </Form.Item>
          <Form.Item
            label="用户名"
            name="username"
            rules={[{ required: true, message: "用户名不可以为空" }]}
          >
            <Input placeholder="请输入用户名"></Input>
          </Form.Item>
          <Form.Item
            label="密码"
            name="password"
            rules={[{ required: true, message: "密码不可以为空" }]}
          >
            <Input placeholder="请输入密码"></Input>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 4 }}>
            <Button type="primary" block htmlType="submit">
              登录
            </Button>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 4 }}>
            <Button
              type="primary"
              danger
              block
              htmlType="button"
              onClick={() => form.resetFields()}
            >
              重置
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};

export default Index;
